package com.csjy.migration.hnnd.business;

import com.csjy.migration.hnnd.DbUtil;
import com.csjy.migration.hnnd.DictTool;
import com.csjy.migration.hnnd.ProgramArgument;
import com.csjy.migration.hnnd.Tool;
import com.csjy.migration.hnnd.annotation.BusinessDataConverter;
import com.csjy.migration.hnnd.dict.Bank;

import javax.script.ScriptException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@BusinessDataConverter(
    auto = false,
    insertSql =  "INSERT INTO ND_BPM_RESPON_COMPENSATORY " +
        "( ID, CREATE_NAME, CREATE_BY, CREATE_DATE, UPDATE_NAME, UPDATE_BY, UPDATE_DATE, SYS_ORG_CODE, SYS_COMPANY_CODE, BPM_STATUS, " +
        " PRO_ID, BANK, COMPENSATORY_TYPE, BANK_ACCOUNT, COMPENSATORY_MONEY, COMPENSATORY_DATE, IN_BAIL, REMARK, COMPENSATORY_INTEREST, LOAN_ID, " +
        " IS_VALID, TASK_ID, PROC_ID, SOURCE_ID, TASK_DEF_KEY, ACTUAL_COMPENSATORY_MONEY, ACTUAL_COMPENSATORY_INTEREST, ACTUAL_COMPENSATORY_DATE, AMORTIZATION, ACCOUNT_NAME, " +
        " BRANCH_NAME, SHARET) VALUES(?,?,?,?,?,?,?,?,?,?," +
        "?,?,?,?,?,?,?,?,?,?," +
        "?,?,?,?,?,?,?,?,?,?," +
        "?,?)",

    updateSql = "UPDATE ND_BPM_RESPON_COMPENSATORY\n" +
        "SET CREATE_NAME=?, CREATE_BY=?, CREATE_DATE=?, UPDATE_NAME=?, UPDATE_BY=?, UPDATE_DATE=?, SYS_ORG_CODE=?, SYS_COMPANY_CODE=?, BPM_STATUS=?, PRO_ID=?, BANK=?, COMPENSATORY_TYPE=?, BANK_ACCOUNT=?, COMPENSATORY_MONEY=?, COMPENSATORY_DATE=?, IN_BAIL=?, REMARK=?, COMPENSATORY_INTEREST=?, LOAN_ID=?, IS_VALID=?, TASK_ID=?, PROC_ID=?, SOURCE_ID=?, TASK_DEF_KEY=?, ACTUAL_COMPENSATORY_MONEY=?, ACTUAL_COMPENSATORY_INTEREST=?, ACTUAL_COMPENSATORY_DATE=?, AMORTIZATION=?, ACCOUNT_NAME=?, BRANCH_NAME=?, SHARET=?\n" +
        "WHERE ID = ?",

    findMigratedIdListSql = "SELECT ID FROM ND_BPM_RESPON_COMPENSATORY WHERE PROC_ID = ?"
)
public class NdBpmResponCompensatory extends AbstractWorkflowBusiness {

  public NdBpmResponCompensatory(DbUtil sourceDbUtil, DbUtil targetDbUtil, SourceBusinessData sourceData, ProgramArgument programArgument, String projectId, String procInstId) throws SQLException {
    super(sourceDbUtil, targetDbUtil, sourceData, programArgument, projectId, procInstId);
  }

  @Override
  public void migrate() throws Exception {
    List<Map> btItemInsteadAuditList = this.sourceData.getBtItemInsteadAuditList().stream()
        .filter(btItemInsteadAudit->btItemInsteadAudit.get("PROCID").toString().equals(this.procInstId))
        .collect(Collectors.toList());

    for(Map.Entry<String,Map<String,Object>> entry : taskParamMap.entrySet()) {
      String curJbpmTaskInstanceId = entry.getKey();
      Map<String,Object> taskParam = entry.getValue();

      for (Map row : btItemInsteadAuditList) {
        try {
          // 判断是否需要覆盖迁移
          int needMigratedResult = this.needMigrated(this.procInstId + "-"+ curJbpmTaskInstanceId + "-"+ row.get("SORTNO"));
          if(needMigratedResult == 0) {
            continue;
          }

          // 单条插入或更新
          if(needMigratedResult == 1) {
            this.targetDbUtil.updateByParams(updateSql,this.buildValues(row, curJbpmTaskInstanceId, taskParam),true);
            // 批量插入或更新 和 单条插入或更新 二选一
//            this.batchUpdateValues.add(this.buildValues(row, curJbpmTaskInstanceId, taskParam));
          } else {
            this.targetDbUtil.updateByParams(insertSql,this.buildValues(row, curJbpmTaskInstanceId, taskParam));
            // 批量插入或更新 和 单条插入或更新 二选一
//            this.batchInsertValues.add(this.buildValues(row, curJbpmTaskInstanceId, taskParam));
          }
        } catch(Exception e) {
          throw new Exception(String.format("流程实例[%s]-任务实例[%s]-代偿数据迁移失败:%s\n",this.procInstId, curJbpmTaskInstanceId, e.getMessage()));
        }
      }
    }
  }

  public List buildValues(Map row, String curJbpmTaskInstanceId, Map<String,Object> taskParam) throws ScriptException, SQLException {
    List values = new ArrayList();
    // ID
    values.add(this.procInstId + "-"+ curJbpmTaskInstanceId + "-"+row.get("SORTNO"));
    // CREATE_NAME
    values.add(null);
    // CREATE_BY
    values.add(row.get("SUBMITEMP"));
    // CREATE_DATE
    values.add(row.get("CREATE_TIME"));
    // UPDATE_NAME
    values.add(null);
    // UPDATE_BY
    values.add(null);
    // UPDATE_DATE
    values.add(row.get("MODIFY_TIME"));
    // SYS_ORG_CODE
    values.add(null);
    // SYS_COMPANY_CODE
    values.add("002");
    // BPM_STATUS
    values.add(1);
    // PRO_ID 项目ID
    values.add(this.projectId);
    // BANK 合作银行 (字典)
    values.add(DictTool.getTargetDictCode(Bank.class,row.get("BANKID")));
    // COMPENSATORY_TYPE 代偿类型
    values.add(row.get("INSTACCTYPE"));
    // BANK_ACCOUNT 银行账号
    values.add(row.get("OCCURACCOUNT"));
    // COMPENSATORY_MONEY 应代偿金额
    values.add(row.get("OUGHTOCCURSUM"));
    // COMPENSATORY_DATE 应代偿时间
    values.add(row.get("OUTGHTTIME"));
    // IN_BAIL 其中用保证金
    values.add(row.get("PROMSUM"));
    // REMARK 备注
    values.add(Tool.decodeUnicode(row.get("INSTACCMEMO")));
    // COMPENSATORY_INTEREST 应代偿利息
    values.add(row.get("OUGHTOCCURLIXI"));
    // LOAN_ID 放款编号
    values.add(row.get("LOANACCOUNTNO"));
    // IS_VALID 是否使用
    values.add("Y");
    // TASK_ID 任务ID
    values.add(curJbpmTaskInstanceId + "-JW");
    // PROC_ID 流程ID
    values.add(this.procInstId + "-JW");
    // TODO: SOURCE_ID 业务id
    values.add(null);
    // TASK_DEF_KEY 节点id
    values.add(taskParam.get("taskDefKey"));
    // ACTUAL_COMPENSATORY_MONEY 实际代偿金额
    values.add(row.get("DEALOCCURSUM"));
    // ACTUAL_COMPENSATORY_INTEREST 实际代偿利息
    values.add(row.get("DEALOCCURLIXI"));
    // ACTUAL_COMPENSATORY_DATE 实际代偿时间
    values.add(row.get("OCCURTIMEBUT"));
    // TODO:AMORTIZATION 他方分摊比例（他放分摊方式选择 自定义分摊)
    values.add(null);
    // ACCOUNT_NAME 开户人名
    values.add(row.get("ACCOUNTNAME"));
    // BRANCH_NAME 分支银行名称
    values.add(row.get("BANKBRANCH"));
    // TODO:SHARET 分摊类型 他方分摊方式 （1：不执行2/8分摊       2：自定义分摊）
    values.add(null);
    return values;
  }
}
